package com.xdtech.trans.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.common.utils.DateUtil;
import com.xdtech.common.utils.DateUtil.DateStyle;
import com.xdtech.sys.aspect.SystemControllerLog;
import com.xdtech.sys.util.SessionContextUtil;
import com.xdtech.sys.vo.UserItem;
import com.xdtech.trans.model.TransWebSite;
import com.xdtech.trans.service.TransOrderService;
import com.xdtech.trans.service.TransWebSiteService;
import com.xdtech.trans.util.TransConstants;
import com.xdtech.trans.vo.PersonItem;
import com.xdtech.trans.vo.TransOrderItem;
import com.xdtech.web.model.Pagination;
import com.xdtech.web.model.ResultMessage;

/**
 * 
 * @author max.zheng
 * @create 2015-05-26 21:56:45
 * @since 1.0
 * @see
 */
@Controller
@Scope("prototype")
public class TransOrderController {
	private Log log = LogFactory.getLog(TransOrderController.class);
	@Autowired
	private TransOrderService transOrderService;
	@Autowired
	private TransWebSiteService transWebSiteService;
	@RequestMapping(value="/transOrder.do",params = "transOrder")
	public ModelAndView skipTransOrder() {
		return new ModelAndView("trans/transOrder/transOrder_ftl");
	}
	@RequestMapping(value="/transOrder.do")
	public ModelAndView scanSkip(String page) {
		return new ModelAndView("trans/transOrder/"+page+"_ftl");
	}
	
	
	@RequestMapping(value="/transOrder.do",params="loadList")
	@ResponseBody
	public Map<String, Object> loadList(TransOrderItem item,Pagination pg) {
		//设置数据权限过滤
		UserItem currentUser = SessionContextUtil.getCurrentUser();
		if (currentUser.isSuperuser())
		{
			//超级管理员移除，数据过滤
			item.getQueryFields().remove("creator");
		}else {
			String currentSubWebsiteIds = "-1";
			if (currentUser instanceof PersonItem) {
				//物流员工
				PersonItem personItem = (PersonItem) currentUser;
				currentSubWebsiteIds = transWebSiteService.getPersonSubWebsiteIdsById(Long.valueOf(personItem.getWebsiteId()));
				item.setCurrentSubWebsiteIds(currentSubWebsiteIds);
			}
			item.getQueryFields().put("currentSubWebsiteIds", currentSubWebsiteIds);
		}
		Map<String, Object> results =  transOrderService.loadPageDataByConditions(pg,item,"findTransOrderByCondition");
		return results;
	}
	
	@RequestMapping(value="/transOrder.do",params = "editTransOrder")
	@SystemControllerLog(description = "编辑")
	public ModelAndView editTransOrder(HttpServletRequest request,Long transOrderId) {
		TransOrderItem item = new TransOrderItem();
		if (transOrderId!=null) {
			item = transOrderService.loadTransOrderItem(transOrderId);
			request.setAttribute("transOrderItem", item);
			request.setAttribute("disabledWebsite", "true");
		}else
		{
			
			item.setOrderStatus("1");//新增
			item.setReceiveTime(DateUtil.getDate(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
			UserItem currentUser = SessionContextUtil.getCurrentUser();
			item.setSalesman(currentUser.getName());
			item.setCreator(currentUser.getLoginName());
			TransWebSite transWebSite = transWebSiteService.getPersonWebsite(currentUser.getId());
			if (transWebSite!=null) {
				request.setAttribute("disabledWebsite", "true");
				item.setPayWebsiteId(transWebSite.getId());
				//设置默认起始网点
				item.setStartWebsiteId(transWebSite.getId());
			}else {
				request.setAttribute("disabledWebsite", "false");
			}
			request.setAttribute("transOrderItem", item);
		}
		return new ModelAndView("trans/transOrder/editTransOrder_ftl");
	}
	
	@RequestMapping(value="/transOrder.do",params = "saveTransOrder")
	@ResponseBody
	@SystemControllerLog(description = "保存")
	public ResultMessage saveTransOrder(TransOrderItem item) {
		ResultMessage r = new ResultMessage();
		//避免前台被修改，重新后台赋值
		UserItem currentUser = SessionContextUtil.getCurrentUser();
		item.setSalesman(currentUser.getName());
		item.setCreator(currentUser.getLoginName());
		item.setOrderForm(TransConstants.FROM_WEB);
		if (transOrderService.saveOrUpdateTransOrder(item)) {
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	
	@RequestMapping(value="/transOrder.do",params = "deleteTransOrderItems")
	@ResponseBody
	@SystemControllerLog(description = "删除")
	public ResultMessage deleteTransOrderItems(String ids) {
		ResultMessage r = new ResultMessage();
		if (StringUtils.isNotEmpty(ids)) {
			String[] tempIds = ids.split(",");
			List<Long> transOrderIds = new ArrayList<Long>();
			for (String id : tempIds) {
				transOrderIds.add(Long.valueOf(id));
			}
			String rs = transOrderService.checkIsCanDel(transOrderIds);
			if (StringUtils.isBlank(rs)) {
				transOrderService.deleteTransOrderInfo(transOrderIds);
			}else {
				r.setSuccess(false);
				r.setMsg(rs);
			}
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	@RequestMapping(value="/transOrder.do",params = "checkTransOrderItems")
	@ResponseBody
	@SystemControllerLog(description = "审核")
	public ResultMessage checkTransOrderItems(String ids) {
		ResultMessage r = new ResultMessage();
		UserItem currentUser = SessionContextUtil.getCurrentUser();
		if (StringUtils.isNotEmpty(ids)) {
			String[] tempIds = ids.split(",");
			List<Long> transOrderIds = new ArrayList<Long>();
			for (String id : tempIds) {
				transOrderIds.add(Long.valueOf(id));
			}
			String rsMsg = transOrderService.checkOrders(transOrderIds,currentUser.getName(),currentUser.getId());
			r.setSuccess(true);
			r.setMsg(StringUtils.isBlank(rsMsg)?"审核通过":rsMsg);
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	
	@RequestMapping(value="/transOrder.do",params = "cancleCheckTransOrderItems")
	@ResponseBody
	@SystemControllerLog(description = "取消审核")
	public ResultMessage cancleCheckTransOrderItems(String ids) {
		ResultMessage r = new ResultMessage();
		UserItem currentUser = SessionContextUtil.getCurrentUser();
		if (StringUtils.isNotEmpty(ids)) {
			String[] tempIds = ids.split(",");
			List<Long> transOrderIds = new ArrayList<Long>();
			for (String id : tempIds) {
				transOrderIds.add(Long.valueOf(id));
			}
			String rsMsg = transOrderService.cancleCheckOrders(transOrderIds,currentUser.getName(),currentUser.getId());
			if (StringUtils.isNotBlank(rsMsg)) {
				r.setSuccess(false);
				r.setMsg(rsMsg);
			}
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	

	@RequestMapping(value="/transOrder.do",params="loadListTracking")
	@ResponseBody
	public Map<String, Object> loadListTracking(String orderNos) {
		Map<String, Object> results =  new HashMap<String, Object>();
//		List<TransOrderTrackingItem> items = new ArrayList<TransOrderTrackingItem>();
//		items.add(new TransOrderTrackingItem(1L,"123456", "2015-5-26 11:30:00", "揽货成功", "营业网点【厦门】已收货，进入公司分拣"));
//		items.add(new TransOrderTrackingItem(2L,"123456", "2015-5-26 14:30:00", "发货成功", "营业网点【厦门】已发货，下一站【上海】"));
//		items.add(new TransOrderTrackingItem(3L,"123456", "2015-5-27 8:30:00", "到达成功","到达网点【上海】"));
//		items.add(new TransOrderTrackingItem(4L,"123456", "2015-5-27 10:30:00", "派件成功", "网点【上海】已派送，派送员：XXX，派送员电话：XXXX"));
//		items.add(new TransOrderTrackingItem(5L,"123456", "2015-5-27 12:30:00", "签收成功", "收货人XXX已签收"));
//		results.put("total", items.size());
//		results.put("rows", items);
		return results;
	}
	
	@RequestMapping(value="/transOrder.do",params = "loadTransOrderInfo")
	@ResponseBody
	public TransOrderItem loadTransOrderInfo(String orderNo) {
		TransOrderItem transOrderItem = new TransOrderItem();
		if (StringUtils.isNotBlank(orderNo)) {
			transOrderItem = transOrderService.loadTransOrderItemByOrderNo(orderNo);
		}
		return transOrderItem;
	}
	
	@RequestMapping(value="/transOrder.do",params = "checkOrderNoIsExit")
	@ResponseBody
	public boolean checkOrderNoIsExit(String id,String orderNo) {
		if(StringUtils.isBlank(id)) id = "0";
		return !transOrderService.checkIsExsit(Long.valueOf(id),orderNo);
	}
	
	/**
	 * 根据重量计算运费
	 * 
	 * @author <a href="max.zheng@zkteco.com">郑志雄</>
	 * @since 2015-7-6 上午9:41:17
	 * @param weight
	 * @return
	 */
	@RequestMapping(value="/transOrder.do",params = "calTotalByWeight")
	@ResponseBody
	public ResultMessage calTotalByWeight(String weight) {
		ResultMessage r = new ResultMessage();
		double total = 0.0;
		if(StringUtils.isNotBlank(weight)) {
			total = transOrderService.calculateTotal(Double.valueOf(weight));
		}
//		System.out.println(total);
		r.setObj(total);
		return r;
	}
	
}
